local frame = CreateFrame("Button", "oApplication", UIParent, "SecureActionButtonTemplate")
local model = CreateFrame("Model", nil, frame)
local macro = "/stopcasting\n/use %s\n/use [button:2] 17; 16"
local tip = GameTooltip
local orig = tip:GetScript"OnTooltipSetItem"

-- From PeriodicTable
local GetID = function(item)
	if type(item) == "number" then return item
	elseif type(item) == "string" then
		local _, _, id = string.find(item, "item:(%d+):%d+:%d+:%d+")
		if id then return tonumber(id) end
	end
end
local S = function() return not TradeFrame:IsShown() and not BankFrame:IsShown() and not MerchantFrame:IsShown() and not MailFrame:IsShown() and not InCombatLockdown() and IsAltKeyDown() end
local E = '23529 28421 23123 23122 18262 21835 43237 6533 6811 34538 31535 6532 20748 20749 2863 3240 25679 3775 2892 2893 8984 8985 43233 20844 22053 22054 43232 12404 12643 36899 36900 23528 28420 7307 3829 25521 23576 2871 3241 6947 6949 6950 8926 43231 8927 8928 21927 43230 20747 23559 23575 20746 5237 20745 20744 6530 34539 2862 3239 3824 34861 6529 7964 7965 22521 22522 20750 10918 10920 10921 10922 22055 43234 43235 '
local OnShow = function(self, ...)
	if(self and orig) then orig(self, ...) end
	local name, id = self:GetItem()
	
	if(name and id) then
		id = GetID(id)
		if(id and E:match(id.."%s") and S()) then
			frame:ClearAllPoints()
			frame:SetAttribute("macrotext", macro:format(name))
			frame:SetAllPoints(GetMouseFocus())
			frame:Show()
		end
	end
end

frame:SetFrameStrata"DIALOG"
frame:RegisterForClicks("LeftButtonUp", "RightButtonUp")
frame:SetScript("OnLeave", function(self) self:Hide() end)
frame:SetAttribute("*type*", "macro")

frame:SetScript("OnEvent", function(self, event, key, state)
	if(event == "MODIFIER_STATE_CHANGED") then
		if(key == "LALT" or key == "RALT") then
			if(not InCombatLockdown() and self:IsShown()) then
				self:ClearAllPoints()
				self:Hide()
			end
		end
	else
		self:ClearAllPoints()
		self:Hide()
	end
end)
frame:RegisterEvent"MODIFIER_STATE_CHANGED"
frame:RegisterEvent"PLAYER_REGEN_DISABLED"

model:SetModel"Interface\\Buttons\\UI-AutoCastButton.mdx"
model:SetAllPoints(frame)
model:SetSequence(0)
model:SetSequenceTime(0, 0)
model:SetScale(1.3)

tip:SetScript("OnTooltipSetItem", OnShow)
